package com.jindy.module.customer.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.jindy.common.core.domain.entity.SysUser;
import com.jindy.common.exception.ServiceException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.module.customer.domain.Customer;
import com.jindy.module.customer.dto.CustomerDto;
import com.jindy.module.customer.mapper.CustomerMapper;
import com.jindy.module.customer.service.ICustomerService;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 客户Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-19
 */
@Service
public class CustomerServiceImpl implements ICustomerService
{
    @Resource
    private CustomerMapper customerMapper;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询客户
     *
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public Customer selectCustomerById(String id)
    {
        return customerMapper.selectCustomerById(id);
    }

    /**
     * 查询客户列表
     *
     * @param customer 客户
     * @return 客户
     */
    @Override
    public List<Customer> selectCustomerList(CustomerDto customer)
    {
        return customerMapper.selectCustomerList(customer);
    }

    /**
     * 模糊查询客户列表
     *
     * @param customer 客户
     * @return 客户
     */
    @Override
    public List<Customer> selectCustomerList2(CustomerDto customer)
    {
        return customerMapper.selectCustomerList2(customer);
    }

    /**
     * 导入客户数据
     *
     * @param customerList 客户数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class);
//    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    @Override
    public String importCustomer(List<Customer> customerList, Boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(customerList) || customerList.size() == 0)
        {
            throw new ServiceException("导入客户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Customer customer : customerList)
        {
            try
            {
                // 验证是否存在这个客户
                Customer u = customerMapper.selectCustomerByName(customer.getName() );

                if (StringUtils.isNull(u))
                {
                    customer.setName(customer.getName());
                    this.insertCustomer(customer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "客户名称" + customer.getName() + " 导入成功");
                }
                else if (updateSupport)
                {
                    customer.setUpdateBy(operName);
                    this.updateCustomer(customer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "客户名称 " + customer.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "客户名称" + customer.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "客户名称" + customer.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增客户
     *
     * @param customer 客户
     * @return 结果
     */
    @Override
    public int insertCustomer(Customer customer)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        customer.setCreateId(sysUser.getUserId().toString());
        customer.setCreateBy(sysUser.getUserName());
        customer.setAllocationTime(DateUtils.getNowDate());
        customer.setCreateTime(DateUtils.getNowDate());
        return customerMapper.insertCustomer(customer);
    }

    /**
     * 修改客户
     *
     * @param customer 客户
     * @return 结果
     */
    @Override
    public int updateCustomer(Customer customer)
    {
        customer.setUpdateTime(DateUtils.getNowDate());
        return customerMapper.updateCustomer(customer);
    }


    /**
     * 批量修改客户
     * @param customer
     * @return 结果
     */
    @Override
    public void updateCustomers(Customer customer)
    {
//        //把String[]转换为list
//        ids = new String[2];
//        ArrayList<String> idList = new ArrayList<String>(ids.length);
//        Collections.addAll(idList, ids);
        if(!CollectionUtils.isEmpty(customer.getIdList())) {
            customer.getIdList().forEach(idVo -> {
                Customer customer1 = customerMapper.selectCustomerById(idVo.getId());
                customer1.setChargePersonId(customer.getChargePersonId());
                customer1.setChargePersonName(customer.getChargePersonName());
                customerMapper.updateCustomer(customer1);
            });
        }
    }

    /**
     * 根据list批量修改客户
     *
     * @param customerList 客户列表
     * @return 结果
     */
    @Override
    public void updateCustomersByList(List<Customer> customerList){
        customerList.forEach(customer->{
            customerMapper.updateCustomer(customer);
        });
    }



    /**
     * 批量删除客户
     *
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteCustomerByIds(String[] ids)
    {
        return customerMapper.deleteCustomerByIds(ids);
    }

    /**
     * 删除客户信息
     *
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteCustomerById(String id)
    {
        return customerMapper.deleteCustomerById(id);
    }
}
